package com.ck.autoconfig.tenant.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import com.ck.autoconfig.tenant.db.TenantDatabaseInterceptor;
import com.ck.autoconfig.tenant.mapper.TenantMapper;
import com.ck.autoconfig.tenant.security.TenantContextWebFilter;
import com.ck.autoconfig.tenant.security.TenantSecurityWebFilter;
import com.ck.autoconfig.tenant.service.TenantService;
import com.ck.autoconfig.tenant.service.TenantServiceImpl;
import com.ck.common.enums.WebFilterOrderEnum;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ck
 * @date 2024/4/11 16:06
 */
@EnableConfigurationProperties(TenantProperties.class)
@ConditionalOnProperty(prefix = "tutuk.tenant", value = "enable", havingValue = "true")
public class TenantAutoConfiguration {

    @Bean
    public TenantService tenantService(TenantMapper tenantMapper){
        return new TenantServiceImpl(tenantMapper);
    }

    // db
    @Bean
    public TenantLineInnerInterceptor tenantLineInnerInterceptor(TenantProperties tenantProperties, MybatisPlusInterceptor interceptor) {
        TenantLineInnerInterceptor inner = new TenantLineInnerInterceptor(new TenantDatabaseInterceptor(tenantProperties));
        // 添加到 interceptor 中
        // 需要加在首位，主要是为了在分页插件前面。这个是 MyBatis Plus 的规定
        List<InnerInterceptor> inners = new ArrayList<>(interceptor.getInterceptors());
        inners.add(0, inner);
        interceptor.setInterceptors(inners);
        return inner;
    }

    // web
    @Bean
    public FilterRegistrationBean<TenantContextWebFilter> tenantContextWebFilter() {
        FilterRegistrationBean<TenantContextWebFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new TenantContextWebFilter());
        registrationBean.setOrder(WebFilterOrderEnum.TENANT_CONTEXT_FILTER);
        return registrationBean;
    }

    // security
    @Bean
    public FilterRegistrationBean<TenantSecurityWebFilter> tenantSecurityWebFilter(TenantProperties tenantProperties,
                                                                                   TenantService tenantService) {
        FilterRegistrationBean<TenantSecurityWebFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new TenantSecurityWebFilter(tenantProperties, tenantService));
        registrationBean.setOrder(WebFilterOrderEnum.TENANT_SECURITY_FILTER);
        return registrationBean;
    }
}
